<template>
  <div class="tags-add">
    <el-dialog :title="text+pageTitle" :visible.sync="dialogFormVisible" width="400px" @close="handleClose">
      <el-form label-width="80px" ref="directorysForm" :model="directorysForm" :rules="directorysFormRule">
        <el-form-item label="所属学科" prop="subjectID" size="small" v-if="isShow">
          <el-select
          v-model="directorysForm.subjectID"
          placeholder="请选择"
          style="width: 100%"
          @focus="handleFocus"
          >
            <el-option
              v-for="item in subjects"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签名称" prop="directoryName" size="small">
          <el-input v-model="directorysForm.directoryName" placeholder="请输入标签名称"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
          <el-button @click="handleClose">{{$t('table.cancel')}}</el-button>
          <el-button type="primary" @click="onSave">{{$t('table.confirm')}}</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/directorys.js'
import { simple } from '@/api/hmmm/subjects.js'
export default {
  data () {
    return {
      dialogFormVisible: false,
      directorysForm: {
        subjectID: '',
        directoryName: ''
      },
      directorysFormRule: {
        subjectID: [{ required: true, message: '请选择所属学科', trigger: 'blur' }],
        directoryName: [{ required: true, message: '请输入目录名称', trigger: 'blur' }]
      },
      subjects: [],
      isShow: true
    }
  },
  props: {
    // 创建or修改
    text: {
      type: String
    },
    // 目录or标签
    pageTitle: {
      type: String
    }
  },
  methods: {
    // 弹层显示
    dialogFormV (row, isShow) {
      this.isShow = isShow
      if (row) this.directorysForm = { ...this.directorysForm, ...row }
      this.dialogFormVisible = true
    },
    // 弹层隐藏
    dialogFormH () {
      this.dialogFormVisible = false
    },
    // 退出
    handleClose () {
      this.dialogFormVisible = false
      this.directorysForm = {
        subjectID: '',
        directoryName: ''
      }
    },
    // 点击确认
    async onSave () {
      try {
        await this.$refs.directorysForm.validate()
        if (this.directorysForm.id) {
          // 修改
          await update(this.directorysForm)
          this.$message.success('修改目录成功')
        } else {
          // 新增
          await add(this.directorysForm)
          this.$message.success('新增目录成功')
        }
        this.$emit('success')
        this.handleClose()
      } catch (err) {
        console.log(err)
      }
    },
    // 获取焦点
    async handleFocus () {
      const { data } = await simple()
      this.subjects = data
    }
  }
}
</script>

<style scoped lang='less'></style>
